<template>
	<view class="content">
		<image class="logo" src="/static/logo.png"></image>
		<view class="text-area">
			<text class="title">{{title}}</text>
		</view>
		<view class="" style="margin-top: 10px;">

		</view>
		<view class="" class="imgsContainerStyle">
			<img @click="delImg(k)" v-for="(v,k) in pics" :key="k" :src="v.src" alt=""
				style="width: 100%;height: 100%;object-fit: cover;">
			<view @click="selectImg()" class="" v-if="pics.length<4"
				style="width: 100%;height: 100%;object-fit: cover;display: flex;justify-content: center;align-items: center;border: 1px solid gainsboro;font-size: 15px;color: gainsboro;">
				点击上传截图
			</view>
		</view>
		<button style="width: 85%;background-color: #3998d8;color: white;" @click="uploadImg()">上传截图</button>

	</view>
</template>

<script>
	export default {
		data() {
			return {
				title: '上传账单截图用于记录花销',
				pics: [],
				base64Imgs: [],
			}
		},
		onLoad() {

		},
		methods: {
			selectImg() {
				let that = this
				uni.chooseImage({
					count: 4, // 设置上传图片数量
					sizeType: ['original', 'compressed'], // ['original', 'compressed']可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], // ['album', 'camera'] album 从相册选图，camera 使用相机，默认二者都有
					success: (chooseImageRes) => {
						const tempFilePaths = chooseImageRes.tempFilePaths
						if ((that.pics.length + tempFilePaths.length) > 4) {
							uni.showModal({
								title: '警告',
								content: '已经超过单次可上传图片的最大上限',
								icon: 'error',
								showCancel: false,
								confirmText: "好的"
							})
						}
						if (!tempFilePaths) {
							uni.showToast({
								title: "选择图片为空",
								icon: 'error'
							})
							return false
						}
						for (let t of tempFilePaths) {
							uni.compressImage({
								src: t,
								quality: 10, //图片压缩质量，0～100，默认80，仅对jpg有效
								success: (res) => {
									let splitStr = res.tempFilePath.split(".")[0]
									splitStr = splitStr.slice(splitStr.length - 32, splitStr
										.length)
									that.pics.push({
										name: splitStr,
										src: res.tempFilePath,
										baseImg: that.toBase64(res.tempFilePath)
									})
								},
								fail(err) {
									console.log('压缩失败==>', err);
								}
							})
						}
					},
					fail() {
						uni.showToast({
							title: "操作失败",
							icon: 'error'
						})
						return false
					}
				})
			},
			toBase64(imgPath) {
				const fs = uni.getFileSystemManager()
				try {
					const res = fs.readFileSync(imgPath, 'base64')
					return res
				} catch (e) {
					console.error(e)
					return ''
				}
			},
			delImg(k) {
				let that = this
				uni.showModal({
					title: "提示",
					content: '是否要删除这个图片',
					success(res) {
						if (res.confirm) that.pics.splice(k, 1)
						return false
					}
				})
			},
			atob(base64) {
				// 定义 Base64 字符集
				const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';

				// 移除字符串中可能的 '=' 填充字符
				base64 = base64.replace(/=+$/, '');

				let binary = '';
				let buffer = 0;
				let bitsCollected = 0;

				for (let i = 0; i < base64.length; i++) {
					const char = base64[i];
					const charIndex = chars.indexOf(char);

					if (charIndex === -1) {
						throw new Error('Invalid character in base64 string');
					}

					// 将 6 位 base64 字符转换为二进制
					buffer = (buffer << 6) | charIndex;
					bitsCollected += 6;

					// 当积累到 8 位时，将其转换为字符
					if (bitsCollected >= 8) {
						bitsCollected -= 8;
						const byte = (buffer >> bitsCollected) & 0xFF;
						binary += String.fromCharCode(byte);
					}
				}
				return binary;
			},
			uploadImg() {
				let that = this
				uni.showModal({
					title: "提示",
					content: "请确保检查无误后上传,以免浪费公共资源！",
					success(res) {
						if (res.confirm) {
							for (let p of that.pics) {
								uniCloud.callFunction({
									name: "uploadImg",
									data: {
										img: p.baseImg
									},
									success(re) {
										try {
											p.parse = JSON.parse(decodeURIComponent(escape(that.atob(re
												.result.payload.result.text))))['pages'][0]['lines']
											uni.reLaunch({
												url: `/pages/addOrder/addOrder?parm=${encodeURIComponent(JSON.stringify(that.pics))}`,
												fail(err) {
													console.log(err);
												}
											})
										} catch (e) {
											uni.showToast({
												title: "图片识别错误",
												icon: "error"
											})
											console.log(e);
										}
									},
									fail(err) {
										console.log("上传图片ocr错误===>", err);
									}
								})
							}
						}
					}
				})
			}

		}
	}
</script>

<style>
	.imgsContainerStyle {
		display: grid;
		grid-template-columns: repeat(auto-fill, minmax(30vw, 1fr));
		grid-template-rows: repeat(2, minmax(30vw, 1fr));
		gap: 10px;
		max-width: 90vw;
		margin: 0 auto;
	}

	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		height: 100vh;
	}

	.logo {
		height: 200rpx;
		width: 200rpx;
		margin-top: 200rpx;
		margin-left: auto;
		margin-right: auto;
		margin-bottom: 50rpx;
	}

	.text-area {
		display: flex;
		justify-content: center;
	}

	.title {
		font-size: 36rpx;
		color: #8f8f94;
	}
</style>